#include "stdafx.h"
#include "MyControls/Clipboard.h"
#include "MyControls/App.h"

namespace My {

void ClipboardCopy(String const & Message, CWnd * Sender)
{
	String::size_type n = Message.find('\n');
	if (n == String::npos)
		return ClipboardCopyAsIs(Message, Sender);

	String Message2 = Message.substr(0, n);
	for (;;) {
		String::size_type e = Message.find('\n', n+1);
		if (e == String::npos)
			break;
		Message2 += '\r';
		Message2 += Message.substr(n, e-n);
		n = e;
	}
	Message2 += '\r';
	Message2 += Message.substr(n);
	ClipboardCopyAsIs(Message2, Sender);
}

void ClipboardCopyAsIs(String const & Message, CWnd * Sender)
{
	if (Sender) {
		if (!Sender->OpenClipboard()) 
			return; 
	}
	else {
		if (!AfxGetMainWnd()->OpenClipboard()) 
			return; 
	}
    EmptyClipboard(); 

	GetApp().BeginActivity("copying data into the clipboard");

	try {
		HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, Message.size() + 1); 
		if (hglbCopy != NULL) { 
			// Lock the handle and copy the text to the buffer. 
			char * lptstrCopy = (char *) GlobalLock(hglbCopy); 
			strcpy(lptstrCopy, Message.c_str());
			GlobalUnlock(hglbCopy); 

			// Place the handle on the clipboard. 
			SetClipboardData(CF_TEXT, hglbCopy); 
		}
		CloseClipboard();
	}
	catch (...) {
		CloseClipboard();
		throw;
	}
	
	GetApp().EndActivity();
}

void ClipboardPaste(String & Message, CWnd * Receiver)
{
	Message.clear();

    if (!IsClipboardFormatAvailable(CF_TEXT)) 
        return; 

	if (Receiver) {
		if (!Receiver->OpenClipboard()) 
			return; 
	}
	else {
		if (!AfxGetMainWnd()->OpenClipboard()) 
			return; 
	}

	GetApp().BeginActivity("pasting data from the clipboard");

	try {
        HGLOBAL hglb = GetClipboardData(CF_TEXT);
        if (hglb != NULL) 
        { 
            char * lptstr = (char *) GlobalLock(hglb); 
            if (lptstr != NULL) 
            { 
				Message = lptstr;
                GlobalUnlock(hglb); 
            } 
        } 
		CloseClipboard();
	}
	catch (...) {
		CloseClipboard();
		throw;
	}
	
	GetApp().EndActivity();
}

bool IsClipboardPasteReady()
{
	return IsClipboardFormatAvailable(CF_TEXT) != 0;
}

} // My
